package com.guomei.controller.curse;

import com.guomei.bean.curse.ReceiveCouponDTO;
import com.guomei.bean.curse.UserCoupon;
import com.guomei.constans.UserCouponCode;
import com.guomei.mapper.curse.CourseMapper;
import com.guomei.service.curse.UserCouponService;
import com.guomei.utils.Result;
import com.guomei.utils.ValidationUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * 用户优惠券控制器
 */
@RestController
@RequestMapping("/api1/user-coupon")
@Slf4j
public class UserCouponController {
    @Resource
    private UserCouponService userCouponService;
    @Resource
    private CourseMapper courseMapper;

    /**
     * 用户领取优惠券
     */
    @PostMapping("/receive")
    public Result<?> receiveCoupon(@Valid @RequestBody ReceiveCouponDTO receiveCouponDTO, BindingResult result) {
        log.info("用户领取优惠券入参：{}", receiveCouponDTO);
        //实体类注解参数校验
        Result commonDataResponse = ValidationUtil.validInputParams(result);
        if (commonDataResponse != null) {
            return commonDataResponse;
        }
        try {
            return userCouponService.receiveCoupon(receiveCouponDTO.getUserId(), receiveCouponDTO.getCouponId());
        } catch (Exception e) {
            log.info("用户领取优惠券失败", e);
            return Result.fail("领取失败");
        }
    }


    /**
     * 判断该优惠卷课程范围
     */
    @PostMapping("/checkCouponScope")
    public Result<?> checkCouponScope(@RequestBody UserCoupon userCoupon) {
        log.info("判断该优惠卷课程范围入参：{}", userCoupon);
        if (userCoupon.getTeacherId() == null){
            return Result.fail("请选择课程老师id");
        }
        return userCouponService.checkCouponScope(userCoupon.getTeacherId());
    }

    /**
     * 根据用户ID查询优惠券列表
     */
    @PostMapping("/userCoupons")
    public Result<?> getUserCoupons(@RequestBody UserCoupon userCoupon) {
        log.info("根据用户ID查询优惠券列表入参：{}", userCoupon);
        try {
            if (userCoupon == null || userCoupon.getPageNum() == null || userCoupon.getPageSize() == null){
                return Result.fail("分页字段信息缺失，查询失败");
            }
            // 验证分页参数是否有效
            if (userCoupon.getPageNum() <= 0 || userCoupon.getPageSize() <= 0) {
                return Result.fail("分页参数无效");
            }
            userCoupon.setStatus(Short.valueOf(String.valueOf(UserCouponCode.NOT_USER.getCode())));
            return userCouponService.getByUserId(userCoupon);
        } catch (NumberFormatException e) {
            log.info("根据用户ID查询优惠券失败", e);
            return Result.fail("根据用户ID查询优惠券失败");
        }

    }
}
